package org.apache.rocketmq.remoting.netty;

import io.netty.channel.Channel;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;

/**
 * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
 * @author：陈清风扬，个人微信号：chenqingfengyangjj。
 * @date:2024/12/27
 * @方法描述：当前类的对象就是要给Runnable，而消息处理器处理请求的操作会被封装成这个Runnable提交给执行器的任务队列，等待执行器执行
 */
public class RequestTask implements Runnable {
    //真正需要执行的任务，处理器处理请求的具体操作就封装在这个任务中
    private final Runnable runnable;
    //当前任务创建的时间，这个时间在计算程序慢速时间时会用到
    private final long createTimestamp = System.currentTimeMillis();
    private final Channel channel;
    private final RemotingCommand request;
    //表示任务是否停止运行的标志
    private volatile boolean stopRun = false;

    //构造方法
    public RequestTask(final Runnable runnable, final Channel channel, final RemotingCommand request) {
        this.runnable = runnable;
        this.channel = channel;
        this.request = request;
    }


    @Override
    public void run() {
        if (!this.stopRun)
            this.runnable.run();
    }


    @Override
    public int hashCode() {

        int result = runnable != null ? runnable.hashCode() : 0;
        result = 31 * result + (int) (getCreateTimestamp() ^ (getCreateTimestamp() >>> 32));
        result = 31 * result + (channel != null ? channel.hashCode() : 0);
        result = 31 * result + (request != null ? request.hashCode() : 0);
        result = 31 * result + (isStopRun() ? 1 : 0);
        return result;
    }


    @Override
    public boolean equals(final Object o) {
        if (this == o)
            return true;
        if (!(o instanceof RequestTask))
            return false;
        final RequestTask that = (RequestTask) o;
        if (getCreateTimestamp() != that.getCreateTimestamp())
            return false;
        if (isStopRun() != that.isStopRun())
            return false;
        if (channel != null ? !channel.equals(that.channel) : that.channel != null)
            return false;
        return request != null ? request.getOpaque() == that.request.getOpaque() : that.request == null;
    }


    public long getCreateTimestamp() {
        return createTimestamp;
    }


    public boolean isStopRun() {
        return stopRun;
    }


    public void setStopRun(final boolean stopRun) {
        this.stopRun = stopRun;
    }


    public void returnResponse(int code, String remark) {
        final RemotingCommand response = RemotingCommand.createResponseCommand(code, remark);
        response.setOpaque(request.getOpaque());
        this.channel.writeAndFlush(response);
    }
}
